//
//  TSWaterfallViewController.m
//  taosha
//
//  Created by lienbao on 16/05/2014.
//  Copyright (c) 2014 com.b5m.taosha. All rights reserved.
//

#import "WSWaterfallViewController.h"
#import "UIComponent.h"

@interface WSWaterfallViewController () <UICollectionViewDataSource, CHTCollectionViewDelegateWaterfallLayout>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) CHTCollectionViewWaterfallLayout *layout;
@property (nonatomic, assign) BOOL isLoadingData;

@end

@implementation WSWaterfallViewController

#pragma mark - getter and setter
- (CHTCollectionViewWaterfallLayout *)layout
{
    if (!_layout) {
        _layout = [[CHTCollectionViewWaterfallLayout alloc] init];
        _layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
        _layout.headerHeight = 0;
        _layout.footerHeight = 0;
        _layout.minimumColumnSpacing = 2.5;
        _layout.minimumInteritemSpacing = 2.5;
    }
    return _layout;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {

        __weak WSWaterfallViewController *blockSelf = self;

        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.layout];
        _collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = self.view.backgroundColor;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.alwaysBounceVertical = YES;
        [self registerClassForCollectionView:_collectionView];
        
        [_collectionView addLegendHeaderWithRefreshingBlock:^{
            if (!blockSelf.isLoadingData) {
                [blockSelf refreshData];
            }
        }];
        
        [_collectionView addLegendFooterWithRefreshingBlock:^{
            if (!blockSelf.isLoadingData) {
                [blockSelf loadMore];
            }
        }];
                
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}

- (NSMutableArray *)cellItems
{
    if (!_cellItems) {
        _cellItems = [NSMutableArray array];
    }
    return _cellItems;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
	// Custom initialization
        self.waterfallCellClassName   = NSStringFromClass([WSWaterfallCell   class]);
        self.waterfallHeaderClassName = NSStringFromClass([WSWaterfallHeader class]);
        self.waterfallFooterClassName = NSStringFromClass([WSWaterfallFooter class]);
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- public method
- (void)refreshData
{
    self.pageIndex = 1;
    self.pageSize  = 10;
    self.isLoadingData = YES;
    [self hiddenEmptyOrErrorView];
}

- (void)stopAnimating
{
    [self.collectionView.header endRefreshing];
    [self.collectionView.footer endRefreshing];
}

- (void)loadDataFinished:(NSArray *)items total:(NSInteger)count
{
    [self stopAnimating];
    self.isLoadingData = NO;
    if ([items count]) {
        self.pageIndex++;
        [self.cellItems addObjectsFromArray:items];
    }
    
    [self.collectionView.footer setHidden:[self.cellItems count] ? NO:YES];
    
    if (!self.cellItems.count) {
        [self showEmptyView];
    }else if (self.cellItems.count >= count) {
        [self.collectionView.footer noticeNoMoreData];
    }
    [self.collectionView reloadData];
}

- (void)loadDataError:(NSError *)error
{
    [self showMessage:[error localizedFailureReason]];
    [self loadDataFinished:nil total:0];
    if (!self.cellItems.count) {
        [self showErrorView];
    }
}

- (void)loadMore
{
    self.isLoadingData = YES;
}

- (void)didEmptyViewCliked:(WSEmptyTipView *)emptyView
{
    [self hiddenEmptyOrErrorView];
    [self.collectionView.header beginRefreshing];
}

- (void)scrollToCollectionViewTop
{
    [self.collectionView scrollRectToVisible:CGRectMake(0, 0, SCREEN_WIDTH, 100) animated:NO];
}

- (void)registerClassForCollectionView:(UICollectionView *)collectionView
{
    [collectionView registerClass:NSClassFromString(self.waterfallCellClassName)
       forCellWithReuseIdentifier:self.waterfallCellClassName];
    [collectionView registerClass:NSClassFromString(self.waterfallHeaderClassName)
       forSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader
	      withReuseIdentifier:self.waterfallHeaderClassName];
    [collectionView registerClass:NSClassFromString(self.waterfallFooterClassName)
       forSupplementaryViewOfKind:CHTCollectionElementKindSectionFooter
	      withReuseIdentifier:self.waterfallFooterClassName];
}

- (void)collectionElementKindSectionHeader:(UICollectionReusableView *)header ForIndexPath:(NSIndexPath*)indexPath
{

}

- (void)collectionElementKindSectionFooter:(UICollectionReusableView *)footer ForIndexPath:(NSIndexPath*)indexPath
{

}

- (UICollectionViewCell *)cellForIndexPath:(NSIndexPath *)indexPath
{
    return [self.collectionView dequeueReusableCellWithReuseIdentifier:self.waterfallCellClassName
							  forIndexPath:indexPath];
}

- (id)cellForDataAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.cellItems objectAtIndex:indexPath.row];
}

- (CGSize)cellForSizeAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeZero;
}

- (void)fillData:(WSWaterfallCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    [cell waterfallCellWithData:[self cellForDataAtIndexPath:indexPath] forIndexPath:indexPath];
}

- (void)didSelectCellAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.cellItems.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WSWaterfallCell *cell = (WSWaterfallCell *)[self cellForIndexPath:indexPath];
    [self fillData:cell atIndexPath:indexPath];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView = nil;
    if ([kind isEqualToString:CHTCollectionElementKindSectionHeader]) {
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                          withReuseIdentifier:self.waterfallHeaderClassName
                                                                 forIndexPath:indexPath];
        [self collectionElementKindSectionHeader:reusableView ForIndexPath:indexPath];
    } else if ([kind isEqualToString:CHTCollectionElementKindSectionFooter]) {
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                          withReuseIdentifier:self.waterfallFooterClassName
                                                                 forIndexPath:indexPath];
        [self collectionElementKindSectionFooter:reusableView ForIndexPath:indexPath];
    }
    return reusableView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self didSelectCellAtIndexPath:indexPath];
}

#pragma mark - CHTCollectionViewDelegateWaterfallLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return [self cellForSizeAtIndexPath:indexPath];
}

@end
